package ltd.followkba.page;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.kcbsdk.ABean;
import com.kcbsdk.EventHandler;
import com.kcbsdk.MyWorks.APhotoInfo;
import com.kcbsdk.MyWorks.AFileInfo;
import com.kcbsdk.MyWorks.AFileType;
import com.kcbsdk.MyWorks.AKclFile;
import com.kcbsdk.MyWorks.AObbligInfo;
import com.kcbsdk.MyWorks.ARecordInfo;
import com.kcbsdk.MyWorks.ATakeInfo;
import com.kcbsdk.MyWorks.AUserSearchType;
import com.kcbsdk.MyWorks.AWorksType;

import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.VARIA;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListener;
import ltd.advskin.base.KcTwoListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.beandbs.BUpWorks;
import ltd.advskin.task.TaskApp3f;
import ltd.advskin.task.TaskFree;
import ltd.advskin.utils.SubUtils;
import ltd.advskin.utils.SysBitmap;
import ltd.advskin.utils.SysUtils;
import ltd.advskin.view.KcBtnProgress;
import ltd.advskin.view.KcHeaderView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.W;
import ltd.followkba.task.App32;
import ltd.followkba.task.App33;
import ltd.followkba.task.App39;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BAppWorks;
import ltd.followkba.task.BDbsAccount;
import ltd.followkba.task.BUploadPlan;
import ltd.followkba.task.EditUtils;
import ltd.followkba.view.CloneView;
import ltd.followkba.view.PlayerView;
import ltd.obbphoto.MOBBW;
import ltd.obbphoto.base.SubFunction;
import ltd.obbphoto.obblig.ObbligStylePage;
import main.MAPI;

import static com.kcbsdk.wpapper.*;
import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class EditUploadPage extends BasePage {
    private CloneView cvUplaod;
    private View kbiCoverUpload;
    private View kbtChangeUpload;
    private View kbtWorksUpload;
    private View tvArtistUpload;
    private View tvInfoUpload;
    private View tvAreaUpload;
    private View tvDateUpload;
    private View tvTimeUpload;
    private View tvIntroUpload;
    private CheckBox cbOriginalUp;
    private CheckBox cbVideoUpload;
    private View llArtistName;
    private View tvSingerStyle;
    private View llSongStyle;
    private View tvSongStyle;
    private KcBtnProgress kbpEnterUp;
    private View tvTagUpload;
    private EditText etIntroUpload;
    private View tvDownloadFlag;
    private View tvSvrFound;
    private View kbtPhotoUpload;
    private PlayerView pvPlayHome;

    private int gPhotoQty;
    private int gAreaCode;
    private byte gWorksType;
    private AFileInfo mAFileInfo;
    private int gClassStyle;
    private APhotoInfo[] mAPhotoInfo;
    private int gAPhotoInfo;
    private int gDownloadFlag;
    private AFileInfo mSvrFound;

    private BAppWorks mBAppWorks;
    private BUploadPlan mBUploadPlan;
    private BDbsAccount mCloneAccount;
    private String gsKeyWord;
    private String gsArtistType;
    private String gsSongStyle;
    private int gCoverWidth;
    private int gCoverHeight;
    private int gTimeLength;
    private boolean skipAPhotoInfo;


    private TaskApp3f mTaskApp3f;
    private boolean isPlaying;
    private boolean isPhotoBlog;


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;

    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_edit_upload);
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            mBUploadPlan = mBaseInput.getInput(0);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvUpload);
        gWorksType = MAPP.mBDbsAccount.WorksType;
        isPhotoBlog = (gWorksType == AWorksType.WORKS_TYPE_PHOTO || gWorksType == AWorksType.WORKS_BLOG_TEXT) ? true : false;
        String text = String.format("编辑上传计划 %s",  MAPP.mWorksName[gWorksType]);
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
        cvUplaod = findViewById(R.id.cvUplaod);
        kbiCoverUpload = findViewById(R.id.kbiCoverUpload);
        kbtChangeUpload = findViewById(R.id.kbtChangeUpload);
        kbtWorksUpload = findViewById(R.id.kbtWorksUpload);
        tvArtistUpload = findViewById(R.id.tvArtistUpload);
        tvInfoUpload = findViewById(R.id.tvInfoUpload);
        tvAreaUpload = findViewById(R.id.tvAreaUpload);
        tvDateUpload = findViewById(R.id.tvDateUpload);
        tvTimeUpload = findViewById(R.id.tvTimeUpload);
        tvIntroUpload = findViewById(R.id.tvIntroUpload);
        etIntroUpload = findViewById(R.id.etIntroUpload);
        cbOriginalUp = findViewById(R.id.cbOriginalUp);
        cbVideoUpload = findViewById(R.id.cbVideoUpload);
        llArtistName = findViewById(R.id.llArtistName);
        tvSingerStyle = findViewById(R.id.tvSingerStyle);
        llSongStyle = findViewById(R.id.llSongStyle);
        tvSongStyle = findViewById(R.id.tvSongStyle);
        kbpEnterUp = findViewById(R.id.kbpEnterUp);
        tvTagUpload = findViewById(R.id.tvTagUpload);
        tvDownloadFlag = findViewById(R.id.tvDownloadFlag);
        tvSvrFound = findViewById(R.id.tvSvrFound);
        kbtPhotoUpload = findViewById(R.id.kbtPhotoUpload);
        pvPlayHome = findViewById(R.id.pvPlayHome);

        cvUplaod.setListener(new KcListener() {
            @Override
            public void onMessage(Object object) {
                switch ((int) object) {
                    case 1:
                        kbpEnterUp.setProgress(2);
                        kbpEnterUp.setText("正在准备作品信息");
                        mSvrFound = null;
                        BAppUser bAppUser = new BAppUser();
                        bAppUser.WorksType = mCloneAccount.CloneAppType;
                        bAppUser.UserIdS = mCloneAccount.CloneUserIdS;
                        if (isPhotoBlog){                                   // 美图及博文
                            if (bAppUser.WorksType == 33){
                                bAppUser.WorksType = 49;                    // 图片
                                App33.setUser(null);                        // App33需要一个默认的账号
                            }
                        }
                        MAPP.startUserHomePage(bAppUser, true);
                        break;
                    case 2:                                 // 保存克隆
                        MAPP.mBDbsAccount.CloneUserIdS = mCloneAccount.CloneUserIdS;
                        MAPP.mBDbsAccount.CloneUserName = mCloneAccount.CloneUserName;
                        MAPP.mBDbsAccount.CloneHead = mCloneAccount.CloneHead;
                        MAPP.mBDbsAccount.CloneAppType = mCloneAccount.CloneAppType;
                        MDBS.setBDbsAccount(MAPP.mBDbsAccount);
                        MTOAST("已经保存克隆", 2000);
                        break;
                    case 3:
                        MAPP.startSelectUserPage(false);
                        break;   // 其他用户
                }
            }
        });
        kbtWorksUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 已复制
                if (mBAppWorks != null) {
                    SubUtils subUtils = new SubUtils();
                    subUtils.copyToClipboard(String.format("%s\n%s", mBAppWorks.WorksName, mBAppWorks.ArtistName));
                }
            }
        });

        kbiCoverUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 封面图片
                if (!isPhotoBlog || mBUploadPlan.PhotoQty == 0){
                    MOBBW.startPhotoLookAtActivity(mBUploadPlan.CoverFile, v);
                }else {
                    if (mBAppWorks.Photos != null){
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int index = 0; index < mBAppWorks.Photos.length; index++){
                            stringBuffer.append(mBAppWorks.Photos[index].FileName);
                            stringBuffer.append(",");
                        }
                        MOBBW.startPhotoLookAtActivity(stringBuffer.toString(), v);
                    }
                }
            }
        });
        kbtChangeUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 换封面
                if (!isPhotoBlog || mBUploadPlan.PhotoQty == 0){
                    MSKIN.setText("正在准备封面...", kbtChangeUpload);
                    MTOAST("正在准备封面...", 2000);
                    mBUploadPlan.CoverFile = null;
                    clickCover(true);
                }
            }
        });
        kbtPhotoUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {         // 按图片信息换封面
                if (!isPhotoBlog || mBUploadPlan.PhotoQty == 0){
                    skipAPhotoInfo = true;
                    getKeyWord(true);
                    MSKIN.setText(String.format("更换到“%s”", gsKeyWord), kbtPhotoUpload);
                    MTOAST(String.format("更换到“%s”", gsKeyWord), 2000);
                    mTaskApp3f = null;
                    mBUploadPlan.CoverFile = null;
                    clickCover(true);
                }
            }
        });

        llArtistName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 已选歌手分类
                MOBBW.startObbligStylePage(gWorksType, false, gClassStyle);  // false表示两项  ture表示三项
            }
        });
        llSongStyle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 已选歌曲分类
                MOBBW.startObbligStylePage(gWorksType, false, gClassStyle);  // false表示两项  ture表示三项
            }
        });
        tvAreaUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 打榜地区
                MOBBW.startAreaCityRankWindow(true, new KcListener() {
                    @Override
                    public void onMessage(Object object) {
                        int areaCode = (int) object;
                        if (areaCode != 0) {
                            gAreaCode = areaCode;
                            showInfo();
                        }
                    }
                });
            }
        });
        tvDateUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 月月-日日
                showDateDialog();
            }
        });
        tvTimeUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 时时:分分
                showTimeDialog();
            }
        });
        tvIntroUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {           // 作品介绍
                String text = etIntroUpload.getText().toString();
                MSKIN.startSkinInputEmoji(false, 200, "作品介绍", text, new KcTwoListener() {
                    @Override
                    public void onMessage(Object object1, Object object2) {
                        etIntroUpload.setText((String) object2);
                    }
                });
            }
        });
        cbOriginalUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                   // 上传原唱
                if (mAFileInfo instanceof AObbligInfo) {
                    AObbligInfo aObbligInfo = (AObbligInfo) mAFileInfo;
                    if (!cbOriginalUp.isChecked()) {
//                        gClassStyle &= ~(1<<KCB_LIST_SRC_FLAG);
                        mBUploadPlan.FileSize = MAPI.GET_FILE_LENGTH(aObbligInfo.AudioFile);
                    } else {
//                        gClassStyle |= ~(1<<KCB_LIST_SRC_FLAG);
                        mBUploadPlan.FileSize = MAPI.GET_FILE_LENGTH(aObbligInfo.OriginalFile);
                    }
                    showInfo();
                }
            }
        });

        kbpEnterUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                   // 确认上传计划
                saveUploadPlan();
            }
        });
        if (mBUploadPlan == null) {
            mBUploadPlan = makeBUploadPlan();
            mBUploadPlan.PlanId = MDBS.getDbsId();
        }
        mCloneAccount = new BDbsAccount();
        mCloneAccount.CloneUserIdS = MAPP.mBDbsAccount.CloneUserIdS;
        mCloneAccount.CloneUserName = MAPP.mBDbsAccount.CloneUserName;
        mCloneAccount.CloneHead = MAPP.mBDbsAccount.CloneHead;
        mCloneAccount.CloneAppType = MAPP.mBDbsAccount.CloneAppType;
        MLOG(String.format("PlanA PlanId %s(%s)%s", mBUploadPlan.PlanId, mCloneAccount.CloneUserIdS, mCloneAccount.CloneUserName));

        cbVideoUpload.setChecked(mBUploadPlan.OnlyAudio);
        kbpEnterUp.setProgress(2);

//        if (false) {
//            TaskApp3f taskApp3f = new TaskApp3f();
//            int table = taskApp3f.keyword2Table(gsKeyWord);
//            MSKIN.delDbsAllItem(VARIA.DBS_PHOTO_NETWORK, table);
//        }
        MAPP.ignoreSSLHandshake();

        if (!isPhotoBlog) {                                                  // 伴奏及K歌
            pvPlayHome.setVisibility(View.VISIBLE);
            pvPlayHome.setListener(new KcListener() {
                @Override
                public void onMessage(Object object) {
                    if (mAFileInfo != null) {
                        if (!isPlaying) {        // 还没有开始播放
                            int timeLength = 0;
                            String worksFile = null;
                            String kclFile = null;
                            if (mAFileInfo instanceof ARecordInfo) {
                                ARecordInfo aRecordInfo = (ARecordInfo) mAFileInfo;
                                worksFile = aRecordInfo.MixAudioFile;
                                kclFile = aRecordInfo.LyricFile;
                                timeLength = aRecordInfo.TimeLength;
                            } else if (mAFileInfo instanceof AObbligInfo) {
                                AObbligInfo aObbligInfo = (AObbligInfo) mAFileInfo;
                                worksFile = aObbligInfo.OriginalFile;
                                kclFile = aObbligInfo.KclFile;
                                timeLength = aObbligInfo.TimeLength;
                            }
                            MLOG(String.format("PlayHomeA %s %s %s", MAPI.GET_FILE_LENGTH(worksFile), MAPI.GET_FILE_LENGTH(kclFile), kclFile));
                            if (timeLength > 0 && MAPI.GET_FILE_LENGTH(worksFile) > 10000) {
                                pvPlayHome.playStart(timeLength, worksFile, kclFile);               // 开始播放云作品
                                isPlaying = true;
                            }
                        } else if (object instanceof Boolean) {
                            MLOG("PlayHomeA " + object);
                        }
                    }
                }
            });
        }
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                getKeyWord(false);
                if (mBUploadPlan.PlanId != 0) {                          // 重新打开的
                    mBAppWorks = MDBS.getBAppWorks(mBUploadPlan.AppType, mBUploadPlan.UserIdS, mBUploadPlan.WorksIdS);
                }
                if (gWorksType < 32 && MAPP.mKcBRankInfo != null){
                    int index = MDBS.getDbsId() % MAPP.mKcBRankInfo.length;
                    if (("全国".equals(MAPP.mKcBRankInfo[index].Name) || "新作".equals(MAPP.mKcBRankInfo[index].Name))){
                        index = MDBS.getDbsId() % MAPP.mKcBRankInfo.length;
                    }
                    gAreaCode = MAPP.mKcBRankInfo[index].AreaData;
                }else {
                    SubFunction subFunction = new SubFunction();
                    gAreaCode = subFunction.getRandomAreaData(false) & 0xffff;
                }
            }
        }).start();

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (methodType > 0) {
                } else {
                    if (mMyWorks.isEventDataRefresh()) {
                        showInfo();
                    }
                }
            }
        });
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        Object object = getPageResult(basePage);
        if (basePage instanceof SelectUserPage) {
            BAppUser bAppUser = (BAppUser) object;
            if (bAppUser != null) {
                mCloneAccount.CloneUserIdS = bAppUser.UserIdS;
                mCloneAccount.CloneUserName = bAppUser.UserName;
                mCloneAccount.CloneHead = bAppUser.HeadFile;
                mCloneAccount.CloneAppType = bAppUser.WorksType;
                MLOG("bAppUser.WorksTypeA "+bAppUser.WorksType);

                if (bAppUser != null && basePage instanceof SelectUserPage) {       // 自动保存
                    MAPP.mBDbsAccount.CloneUserIdS = mCloneAccount.CloneUserIdS;
                    MAPP.mBDbsAccount.CloneUserName = mCloneAccount.CloneUserName;
                    MAPP.mBDbsAccount.CloneHead = mCloneAccount.CloneHead;
                    MAPP.mBDbsAccount.CloneAppType = mCloneAccount.CloneAppType;
                    MDBS.setBDbsAccount(MAPP.mBDbsAccount);
                    MTOAST("已经保存克隆", 2000);
                }

            }
            showInfo();
        }
        if (basePage instanceof UserHomePage) {
            if (object instanceof BAppWorks) {
                mBAppWorks = (BAppWorks) object;
                new TaskFree(null, new TaskFree.Listener() {
                    @Override
                    public void onMessage(boolean isThread, Object object) {
                        if (isThread) {
                            if (mBAppWorks != null) {
                                makeBAppWorks(mBAppWorks);
                            }
                            return;
                        }
                        showInfo();
                        kbpEnterUp.setProgress(2 + 100);
                        kbpEnterUp.setText("确认上传计划");
                    }
                });
                showInfo();
            }
        }
        if (basePage instanceof ObbligStylePage) {
            if (object instanceof Integer) {
                gClassStyle = (int) object;
                showInfo();
            }
        }
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        if (pvPlayHome != null){
            pvPlayHome.release();
        }
        setClose();
    }
    private void showInfo() {
        cvUplaod.setInfo(mCloneAccount);
        tvArtistUpload.setVisibility(View.GONE);        // 歌手
        llArtistName.setVisibility(View.GONE);       // llArtistName
        llSongStyle.setVisibility(View.GONE);       // llSongStyle
        cbOriginalUp.setVisibility(View.GONE);          // cbSourceUpload 上传原唱
        cbVideoUpload.setVisibility(View.GONE);
        kbtChangeUpload.setVisibility(View.GONE);
        tvDownloadFlag.setVisibility(View.GONE);

        String text = mMyUtils.getAreaDataRankName(gAreaCode);
        MSKIN.setText(text, tvAreaUpload);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        MSKIN.setText(sdf.format(mBUploadPlan.SetTick), tvDateUpload);
        sdf = new SimpleDateFormat("HH:mm");
        MSKIN.setText(sdf.format(mBUploadPlan.SetTick), tvTimeUpload);
        MSKIN.setText(mBUploadPlan.Intro, etIntroUpload);
        if (mBAppWorks != null) {
            if (!isPhotoBlog || mBUploadPlan.PhotoQty == 0){
                kbtChangeUpload.setVisibility(View.VISIBLE);
                kbtPhotoUpload.setVisibility(View.VISIBLE);
            }else {
                kbtChangeUpload.setVisibility(View.GONE);
                kbtPhotoUpload.setVisibility(View.GONE);
            }

            if (mBUploadPlan.CoverFile != null) {
                MSKIN.showWorksCover(mBUploadPlan.CoverFile, kbiCoverUpload);
                if (gAPhotoInfo == 0) {
                    MSKIN.setText(String.format("换封面(%s)", gPhotoQty), kbtChangeUpload);
                } else {
                    MSKIN.setText(String.format("换封面(%s/%s)", gAPhotoInfo % gPhotoQty, gPhotoQty), kbtChangeUpload);
                }
                MSKIN.setText(String.format("%sx%s", gCoverWidth, gCoverHeight), kbtPhotoUpload);
            } else {
                MSKIN.showWorksCover(mBAppWorks.CoverFile, kbiCoverUpload);
            }
            MAPP.showWorksName(mBUploadPlan.WorksName, gWorksType, false, mBAppWorks.IsVideo, kbtWorksUpload);
            if (mBAppWorks.IsVideo) {
                cbVideoUpload.setVisibility(View.VISIBLE);          // 只上传音频
            }
            if (gWorksType == AWorksType.WORKS_OBB_SONG || gWorksType == AWorksType.WORKS_OBB_RECITE) {        // 伴奏
                cbOriginalUp.setVisibility(View.VISIBLE);       // cbSourceUpload 上传原唱
            }
            DecimalFormat df2 = new DecimalFormat("0.00 ");
            kbpEnterUp.setVisibility(View.VISIBLE);
            if (!isPhotoBlog){               // 伴奏及K歌
                tvArtistUpload.setVisibility(View.VISIBLE);        // 歌手
                tvSvrFound.setVisibility(View.VISIBLE);         // 从服务器找到相同的
                if (gWorksType == AWorksType.WORKS_SING_SONG || gWorksType == AWorksType.WORKS_OBB_SONG) {
                    MSKIN.setText(String.format("歌手：%s", mBAppWorks.ArtistName), tvArtistUpload);
                } else {
                    MSKIN.setText(String.format("作者：%s", mBAppWorks.ArtistName), tvArtistUpload);
                }
                llArtistName.setVisibility(View.VISIBLE);       // llArtistName
                llSongStyle.setVisibility(View.VISIBLE);       // llSongStyle
                gsArtistType = MOBBW.getArtistType(gWorksType, gClassStyle);
                gsSongStyle = MOBBW.getObbligClassStyle(gWorksType, gClassStyle);
                MSKIN.setText(gsArtistType, tvSingerStyle);         // 歌手类型
                MSKIN.setText(gsSongStyle, tvSongStyle);     // 歌曲类型
                text = getDownloadFlag();
                if (text != null) {
                    if (!cbOriginalUp.isChecked() && text.indexOf("原唱") >= 0) {       // 原唱文件出错 // 同时上传原唱到在K歌作品
                    } else {
                        tvDownloadFlag.setVisibility(View.VISIBLE);
                        MSKIN.setText(text, tvDownloadFlag);     // ERROR
                    }
                }
                if (mSvrFound != null) {                // 从服务器找到匹配伴奏
                    if (!cbOriginalUp.isChecked()){     // 不是原唱
                        if (gWorksType == AWorksType.WORKS_RECITATION || gWorksType == AWorksType.WORKS_SING_SONG) {        // K歌
                            text = String.format("服务器伴奏ID:%s_%04x", mSvrFound.UserID, mSvrFound.FileID);
                        } else {                                                                                             // 伴奏
                            text = String.format("伴奏ID:%s_%04x 已被别人分享过了", mSvrFound.MusicID0, mSvrFound.MusicID1);
                            kbpEnterUp.setVisibility(View.GONE);
                        }
                    }else {                             // 选择了原唱
                        if (gWorksType == AWorksType.WORKS_OBB_RECITE || gWorksType == AWorksType.WORKS_OBB_RECITE) {        // 伴奏
//                            text = "可分享原唱";
                            text = String.format("服务器伴奏ID:%s_%04x", mSvrFound.UserID, mSvrFound.FileID);
                        }
                    }
                } else {                            // 服务器没有匹配伴奏
                    if (gWorksType == AWorksType.WORKS_RECITATION || gWorksType == AWorksType.WORKS_SING_SONG) {        // K歌
                        text = "服务器没有匹配伴奏，不建议上传";
                    } else {                                 // 伴奏
                        if (!cbOriginalUp.isChecked()){     // 不是原唱
                            text = "可分享伴奏";
                        }else {                             // 原唱
                            text = "服务器没有匹配伴奏，不建议上传";
                        }
                    }
                }

                MSKIN.setText(text, tvSvrFound);
                double length = (double) mBUploadPlan.FileSize / 1024.0 / 1024.0;
                if (mBAppWorks.IsVideo && !cbVideoUpload.isChecked()) {
                    length = (double) mBUploadPlan.VideoSize / 1024.0 / 1024.0;
                }
                if (mBUploadPlan.KclSize != 0) {
                    if (mBAppWorks.WorksName.indexOf("自由K诗") >= 0){
                        text = String.format("作品名包含“自由K诗”，不建议上传");
                    }else {
                        double kclSize = (double) mBUploadPlan.KclSize / 1024.0;
                        text = String.format("作品大小：%sM %02d:%02d 歌词：%sK", df2.format(length), mBAppWorks.TimeLength / 1000 / 60, mBAppWorks.TimeLength / 1000 % 60, df2.format(kclSize));
                    }
                }else {
                    text = String.format("没有歌词，不建议上传");
                }
            } else {                 // isPhotoBlog 图片
                if (MAPI.isEmpty(mBUploadPlan.Intro)){                                  // 没有写入介绍
                    text = String.format("没有作品介绍，不建议上传");
                }else {
                    if (mBUploadPlan.PhotoQty > 0) {
                        double length = (double) mBUploadPlan.FileSize / 1024.0;
                        text = String.format("图片文件大小：%sK 共%d张", df2.format(length), mBUploadPlan.PhotoQty);
                    } else if (MAPI.GET_FILE_LENGTH(mBUploadPlan.CoverFile) > 0) {
                        double length = (double) MAPI.GET_FILE_LENGTH(mBUploadPlan.CoverFile) / 1024.0;
                        text = String.format("手工添加图片1张，文件大小：%sK", df2.format(length));
                    } else {
                        text = String.format("需要手工添加图片");
                    }
                }
            }
            MSKIN.setText(text, tvInfoUpload);
            MSKIN.setText(mBAppWorks.SrcTag, tvTagUpload);     // tvTagUpload
        } else {
            MSKIN.showWorksCover((String)null, kbiCoverUpload);
            MSKIN.setText(String.format("还没有选择"), kbtWorksUpload);
            MSKIN.setText("", etIntroUpload);
        }
    }


    private void makeBAppWorks(BAppWorks bAppWorks){
        mBUploadPlan.WorksName = bAppWorks.WorksName;
        mBUploadPlan.Intro = bAppWorks.Intro;
        mAPhotoInfo = null;
        gAPhotoInfo = 0;
        gDownloadFlag = 0;
        gClassStyle = 0;

        EditUtils editUtils = new EditUtils();
        MLOG(String.format("UploadA make A %s %s %s", gWorksType, bAppWorks.WorksType, bAppWorks.WorksName));
        if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.CoverUrl, bAppWorks.CoverFile))) {
            gDownloadFlag |= 0x80;
            MLOGE(String.format("WORKS_OBB_SONG E80 %s", bAppWorks.CoverUrl));
        }
        setCoverFile(bAppWorks.CoverFile);
//        MLOG(String.format("UploadA make B %s", bAppWorks.WorksName));
        switch (gWorksType) {
            case AWorksType.WORKS_SING_SONG:                       // K歌类
            case AWorksType.WORKS_RECITATION:
            case AWorksType.WORKS_TYPE_APP21:
                ARecordInfo aRecordInfo = new ARecordInfo();
                aRecordInfo.MusicID0 = bAppWorks.WorksType;
                aRecordInfo.MusicID1 = MAPI.STRING_DEC32(bAppWorks.MusicIdS);
                if (bAppWorks.IsVideo) {
                    aRecordInfo.MixVideoFile = String.format("%sV%02x_%s.mp4", MRAM.gsCachePath, aRecordInfo.MusicID0, aRecordInfo.MusicID1);
                    if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.VideoUrl, aRecordInfo.MixVideoFile))) {
                        gDownloadFlag |= 0x01;
                        MLOGE(String.format("WORKS_OBB_SONG E1 %s", bAppWorks.VideoUrl));
                    }
                    mBUploadPlan.VideoSize = MAPI.GET_FILE_LENGTH(aRecordInfo.MixVideoFile);
                }
                MTOAST("正在下载音频文件", 2000);
                aRecordInfo.MixAudioFile = String.format("%sA%02x_%s.mp3", MRAM.gsCachePath, aRecordInfo.MusicID0, aRecordInfo.MusicID1);
                if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.AudioUrl, aRecordInfo.MixAudioFile))) {
                    gDownloadFlag |= 0x02;
                    MLOGE(String.format("WORKS_OBB_SONG E2 %s", bAppWorks.AudioUrl));
                }
                mBUploadPlan.FileSize = MAPI.GET_FILE_LENGTH(aRecordInfo.MixAudioFile);
                if (MAPI.IS_FILE_DONE(aRecordInfo.MixAudioFile)){
                    gTimeLength = 0;
                    SysUtils sysUtils = new SysUtils();
                    sysUtils.calculationTimeLength(aRecordInfo.MixAudioFile, new KcListener() {
                        @Override
                        public void onMessage(Object object) {
                            if (object instanceof Integer) {
                                gTimeLength = (int)object;
                            }
                        }
                    });
                    for (int waitting = 30; waitting != 0; waitting--){
                        if (gTimeLength != 0){
                            break;
                        }
                        MSLEEP(100);
                    }
                }
                MLOG(String.format("WORKS_OBB_SONG gTimeLength %s %s", gTimeLength, bAppWorks.TimeLength));
                aRecordInfo.TimeLength = gTimeLength;  // 获取音频的时间
                mBAppWorks.TimeLength = gTimeLength;
                aRecordInfo.LyricFile = String.format("%sA%02x_%s.kcl", MRAM.gsCachePath, aRecordInfo.MusicID0, aRecordInfo.MusicID1);
//MAPI.DEL_FILE_DONE(aObbligInfo.KclFile);
                if (!"ok".equals(editUtils.downloadLyricFile(bAppWorks.LyricUrl, aRecordInfo.LyricFile))){
                    gDownloadFlag |= 0x08;
                    MLOGE(String.format("WORKS_OBB_SONG E08 %s", bAppWorks.LyricUrl));
                }
                mBUploadPlan.KclSize = MAPI.GET_FILE_LENGTH(aRecordInfo.LyricFile);
                MLOG(String.format("WORKS_OBB_SONG aRecordInfo.KclFile %s %s", MAPI.GET_FILE_LENGTH(aRecordInfo.LyricFile), aRecordInfo.LyricFile));
                MTOAST(String.format("正在查找服务器“%s”", bAppWorks.WorksName), 2000);
                if (gWorksType != AWorksType.WORKS_TYPE_APP21) {
                    AUserSearchType aUserSearchType = (gWorksType == AWorksType.WORKS_SING_SONG) ? AUserSearchType.LIST_SEARCH_OBB_NORMAL: AUserSearchType.LIST_SEARCH_REC_NORMAL;
                    if (searchWorks(aUserSearchType, bAppWorks, aRecordInfo.LyricFile)) {
                        aRecordInfo.MusicID0 = mSvrFound.UserID;      // 在K歌之中，找到服务器的伴奏，就使用我们的ID
                        aRecordInfo.MusicID1 = mSvrFound.FileID;
                        if (mSvrFound != null) {
                            gClassStyle = mSvrFound.ClassStyle;
                        }
//                        aRecordInfo.KclFile = null;
                    }
                }
                mAFileInfo = aRecordInfo;
                break;
            case AWorksType.WORKS_OBB_SONG:                        // 伴奏类
            case AWorksType.WORKS_OBB_RECITE:
                AObbligInfo aObbligInfo = new AObbligInfo();
                aObbligInfo.MusicID0 = bAppWorks.WorksType;
                aObbligInfo.MusicID1 = MAPI.STRING_DEC32(bAppWorks.MusicIdS);
                MLOG(String.format("UploadA make C %s", bAppWorks.WorksName));
                if (bAppWorks.WorksType == 39){
                    MTOAST("正在获取PoemInfo", 2000);
                    BAppWorks works = App39.getPoemInfo(bAppWorks.MusicIdS);
                    if (works != null){
                        bAppWorks.MusicUrl = works.MusicUrl;                // 需要补充这两个Url
                        bAppWorks.OriginalUrl = works.OriginalUrl;
                    }
                }
                aObbligInfo.AudioFile = String.format("%sM%02x_%s.mp3", MRAM.gsCachePath, aObbligInfo.MusicID0, aObbligInfo.MusicID1);
                MTOAST("正在下载音频文件", 2000);
                if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.MusicHqUrl, aObbligInfo.AudioFile))) {
                    if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.MusicUrl, aObbligInfo.AudioFile))) {
                        gDownloadFlag |= 0x10;
                        MLOGE(String.format("WORKS_OBB_SONG E1 %s(%s)", bAppWorks.MusicHqUrl, bAppWorks.MusicUrl));
                    }
                }

                if (MAPI.IS_FILE_DONE(aObbligInfo.AudioFile)){
                    gTimeLength = 0;
                    SysUtils sysUtils = new SysUtils();
                    MTOAST("正在计算时长", 2000);
                    MLOG(String.format("UploadA make D %s %s", MAPI.GET_FILE_LENGTH(aObbligInfo.AudioFile), aObbligInfo.AudioFile));
                    sysUtils.calculationTimeLength(aObbligInfo.AudioFile, new KcListener() {
                        @Override
                        public void onMessage(Object object) {
                            if (object instanceof Integer) {
                                gTimeLength = (int)object;
                            }
                        }
                    });
                    for (int waitting = 30; waitting != 0; waitting--){
                        if (gTimeLength != 0){
                            break;
                        }
                        MSLEEP(100);
                    }
               }
                MLOG(String.format("UploadA gTimeLength %s %s", gTimeLength, bAppWorks.TimeLength));
                aObbligInfo.TimeLength = gTimeLength;
                mBAppWorks.TimeLength = gTimeLength;
                mBUploadPlan.FileSize = MAPI.GET_FILE_LENGTH(aObbligInfo.AudioFile);
                aObbligInfo.KclFile = String.format("%sA%02x_%s.kcl", MRAM.gsCachePath, aObbligInfo.MusicID0, aObbligInfo.MusicID1);
//MAPI.DEL_FILE_DONE(aObbligInfo.KclFile);
                MTOAST("正在下载歌词文件", 2000);
                if (!"ok".equals(editUtils.downloadLyricFile(bAppWorks.LyricUrl, aObbligInfo.KclFile))){
                    gDownloadFlag |= 0x08;
                    MLOGE(String.format("WORKS_OBB_SONG E8 %s", bAppWorks.LyricUrl));
                }else {
                    AKclFile aKclFile = MAPI.READ_KCL_FILE(aObbligInfo.KclFile);
                    if (aKclFile != null) {
                        MLOG(String.format("UploadA B %02x %s %s %s", gDownloadFlag, MAPI.GET_FILE_LENGTH(aObbligInfo.KclFile), aObbligInfo.KclFile, aKclFile.Lines != null ? aKclFile.Lines.length : 0));
                        mBUploadPlan.KclSize = MAPI.GET_FILE_LENGTH(aObbligInfo.KclFile);
                    }else {
                        MLOGE(String.format("WORKS_OBB_SONG Q 歌词出错%s %s %s", gDownloadFlag, MAPI.GET_FILE_LENGTH(aObbligInfo.KclFile), bAppWorks.LyricUrl));
                    }
                }
                aObbligInfo.OriginalFile = String.format("%sS%02x_%s.mp3", MRAM.gsCachePath, aObbligInfo.MusicID0, aObbligInfo.MusicID1);
                MTOAST("正在下载原唱文件", 2000);
                if (!"ok".equals(editUtils.downloadUrlFile(bAppWorks.OriginalUrl, aObbligInfo.OriginalFile))) {
                    gDownloadFlag |= 0x20;
                    MLOGE(String.format("WORKS_OBB_SONG E20 %s", bAppWorks.OriginalUrl));
                }

                if (!MAPI.isEmpty(bAppWorks.SrcTag)) {
                    gClassStyle = MOBBW.obbligTagToFlag(gWorksType, bAppWorks.SrcTag);
                    if (bAppWorks.SrcTag.length() > 5){
                        mBUploadPlan.Intro = bAppWorks.SrcTag;
                    }
                }else {
                    String[] array = MSKIN.getStringArray((gWorksType == AWorksType.WORKS_OBB_SONG) ? R.array.obb_auto_intro : R.array.obb_rec_intro);
                    String text = null;
                    for (int index = 0; index < 5; index++) {
                        text = array[MDBS.getDbsId() % array.length];
                        int start = text.indexOf("#L");
                        if (start >= 0) {      // 需要插入歌词
                            int qty = MAPI.STRING_DEC32(text.substring(start + 2));
                            if (qty > 0) {
                                String lyric = editUtils.getLyricLine(qty, aObbligInfo.KclFile);
                                if (lyric != null) {
                                    text = text.replace(String.format("#L%s", qty), lyric);
                                    break;
                                }
                            }
                        }
                    }
                    mBUploadPlan.Intro = text;
                }
                MLOG(String.format("UploadA make D %s", bAppWorks.WorksName));
                famousHead(bAppWorks);
                changeAPhotoInfo();

//                String srcTag = "女声类 流行 情歌 经典老歌 浴室 云 伤感 中青年 70后 苦情歌 婉约派 抒情歌曲 微凉 主流 女声类 成熟系 中等力度 中音 独唱 适中难度 粤语 港台 90年代 原唱";
//                int classStyle = MOBBW.obbligTagToFlag(AWorksType.WORKS_SING_SONG, srcTag);
//                MLOG(String.format("WORKS_OBB_SONG C2 %08x %s %s", classStyle, mAPhotoInfo[0].FileUrl, mAPhotoInfo[0].FileName));
                MLOG(String.format("UploadA A %s %s %s", aObbligInfo.TimeLength, MAPI.GET_FILE_LENGTH(aObbligInfo.AudioFile), aObbligInfo.AudioFile));

                MTOAST(String.format("正在查找服务器“%s”", bAppWorks.WorksName), 2000);
                AUserSearchType aUserSearchType = (gWorksType == AWorksType.WORKS_OBB_SONG) ? AUserSearchType.LIST_SEARCH_OBB_NORMAL: AUserSearchType.LIST_SEARCH_REC_NORMAL;
                if (searchWorks(aUserSearchType, bAppWorks, aObbligInfo.KclFile)) {
                    if (mSvrFound != null) {
                        aObbligInfo.MusicID0 = mSvrFound.MusicID0;
                        aObbligInfo.MusicID1 = mSvrFound.MusicID1;
                        gClassStyle = mSvrFound.ClassStyle;
                    }
                    aObbligInfo.KclFile = null;
                }
                mAFileInfo = aObbligInfo;
                break;

            case AWorksType.WORKS_TYPE_PHOTO:
            case AWorksType.WORKS_BLOG_TEXT:
                if (bAppWorks.Photos != null && bAppWorks.Photos.length > 0) {
                    int fileSize = 0;
                    for (int index = 0; index < bAppWorks.Photos.length; index++) {
                        String fileName = bAppWorks.Photos[index].FileName;
                        if (gWorksType == AWorksType.WORKS_TYPE_PHOTO) {
                            editUtils.downloadPhoto(false, 1024, 1024, bAppWorks.Photos[index].FileUrl, fileName);
                        }else {
                            editUtils.downloadPhoto(false, 1280, (int)((float)1280 * (16.0/9.0)), bAppWorks.Photos[index].FileUrl, fileName);
                        }
                        fileSize += MAPI.GET_FILE_LENGTH(fileName);
                        MLOG(String.format("downloadPhoto %s %s %s", index, MAPI.GET_FILE_LENGTH(fileName), fileName));
                    }
                    mBUploadPlan.FileSize = fileSize;
                    mBUploadPlan.PhotoQty = bAppWorks.Photos.length;
                }else {
                    mBUploadPlan.FileSize = 0;
                    mBUploadPlan.PhotoQty = 0;
                }
                if (MAPI.isEmpty(bAppWorks.Intro) || bAppWorks.Intro.length() < 3){          // 没有写入介绍或者太短
                    if (bAppWorks.Trends != null){
                        int length = bAppWorks.Trends.length > 2 ? 2 : bAppWorks.Trends.length;
                        for (int index = 0; index < length; index++) {
                            mBUploadPlan.WorksName = bAppWorks.Trends[index] + " ";
                        }
                        StringBuffer stringBuffer = new StringBuffer();
                        int counter = bAppWorks.Trends.length - 1;
                        for (int index = 0; index < bAppWorks.Trends.length; index++) {
                            stringBuffer.append("#");
                            stringBuffer.append(bAppWorks.Trends[counter - index]);
                            stringBuffer.append("# \n");
                        }
                    }
                }
                if (MAPI.isEmpty(bAppWorks.Intro) || bAppWorks.Intro.length() < 3) {          // 没有写入介绍或者太短
                    Random random = new Random();
                    if (mBUploadPlan.PhotoQty > 0) {
                        String[] worksName = MSKIN.getStringArray(R.array.auto_works_name);
                        bAppWorks.WorksName = String.format(worksName[Math.abs(random.nextInt() % worksName.length)], mBUploadPlan.PhotoQty);
                    }else {
                        bAppWorks.WorksName = "分享图片";
                    }
                    String[] intro = MSKIN.getStringArray(R.array.auto_photo_intro);
                    mBUploadPlan.Intro = String.format("%s，%s", bAppWorks.WorksName, intro[Math.abs(random.nextInt() % intro.length)]);
                }

                if (bAppWorks.WorksName == null) {
                    bAppWorks.WorksName = MOBBW.autoTitle(bAppWorks.Intro);
                }
                if (gWorksType == AWorksType.WORKS_TYPE_PHOTO) {
                    APhotoInfo aPhotoInfo = new APhotoInfo();
                    mAFileInfo = aPhotoInfo;
                }else {
                    ATakeInfo aTakeInfo = new ATakeInfo();
                    mAFileInfo = aTakeInfo;
                }
                MLOG(String.format("UploadA aPhotoInfo A %s(%s)", bAppWorks.WorksName ,  mBUploadPlan.Intro));
                break;
        }
        if (mAFileInfo != null) {
            mAFileInfo.WorksType = gWorksType;
        }
        MLOG(String.format("UploadA make W %s", bAppWorks.WorksName));
    }

    private void saveUploadPlan() {
        if (mBAppWorks == null){
            MTOAST("请选择克隆作品", 2000);
            return;
        }
        if (mAFileInfo == null) {
            MTOAST("上传计划不正常，请重新设置", 2000);
            return;
        }
       String text = getDownloadFlag();
        if (text != null){
            if (!cbOriginalUp.isChecked()  && text.indexOf("原唱") >= 0) {       // 原唱文件出错 // 同时上传原唱到在K歌作品
            }else {
                MTOAST("下载 " + text, 2000);
                return;
            }
        }
        SysBitmap sysBitmap = new SysBitmap();
        int g4Local_1 = sysBitmap.getBitmapSize(mBUploadPlan.CoverFile);
        if (g4Local_1 == 0){
            MTOAST("需要选择封面", 2000);
            return;
        }
        int width = g4Local_1 >> 16;
        int height = g4Local_1 & 0xffff;
        if (width != height || MAPI.GET_FILE_LENGTH(mBUploadPlan.CoverFile) > 88000){       // 封面不是正方形或者太大了
            int size = width < height ? width : height;
            if (size > 800){
                size = 800;
            }
            Bitmap bitmap = sysBitmap.getReqBitmap(size, size, 0, 0, 0, 0, 0, mBUploadPlan.CoverFile);
            mBUploadPlan.CoverFile = null;
            if (bitmap != null) {
                String temp1 = String.format("%s%sa.jpg", MRAM.gsCachePath, mBUploadPlan.PlanId);
                sysBitmap.saveBitmapFile(bitmap, temp1);
                int length = MAPI.GET_FILE_LENGTH(temp1);
                if (length > 500){
                    if (length > 88000){
                        String temp2 = String.format("%s%sb.jpg", MRAM.gsCachePath, mBUploadPlan.PlanId);
                        if (sysBitmap.maxImgFlieSize(88000, temp1, temp2)){
                            setCoverFile(temp2);
                        }
                    }else {
                        setCoverFile(temp1);
                    }
                }
                bitmap.recycle();
            }
        }
        if (MAPI.isEmpty(mBUploadPlan.CoverFile)){
            MTOAST("封面文件不正确", 2000);
            return;
        }

        if (gWorksType == AWorksType.WORKS_SING_SONG || gWorksType == AWorksType.WORKS_RECITATION || gWorksType == AWorksType.WORKS_OBB_SONG || gWorksType == AWorksType.WORKS_OBB_RECITE) {        // 伴奏及K歌
            if (mAFileInfo.TimeLength == 0){
                MTOAST("没有时长，需要重新选择", 2000);
                return;
            }
            if (MAPI.isEmpty(gsArtistType) || MAPI.isEmpty(gsSongStyle)){
                MTOAST(getString(ltd.obbphoto.R.string.no_choice_singers_songs), 2000);
                return;
            }
        }
        BUpWorks bUpWorks = new BUpWorks();
        mBUploadPlan.mBUpWorks = bUpWorks;
        bUpWorks.WorksType = gWorksType;
        bUpWorks.UserID = MAPP.mBDbsAccount.UserID;
        bUpWorks.mAFileInfo = mAFileInfo;

        mBUploadPlan.DoneTick = 0;                      // 重新开始
        MDBS.setFreeText(0, "UPLOAD_DATE_TIME", String.format("%s", mBUploadPlan.SetTick));
        mBUploadPlan.OnlyAudio = cbVideoUpload.isChecked();
        if (mBAppWorks.IsVideo && !mBUploadPlan.OnlyAudio) {
            mBUploadPlan.IsVideo = true;
        } else {
            mBUploadPlan.IsVideo = false;
        }
        mBUploadPlan.Intro = etIntroUpload.getText().toString();
        mBUploadPlan.Area = mMyUtils.getAreaDataRankName(gAreaCode);
        mBUploadPlan.AppType = mCloneAccount.CloneAppType;
        mBUploadPlan.UserIdS = mCloneAccount.CloneUserIdS;
        mBUploadPlan.UserName = mCloneAccount.CloneUserName;

        mBUploadPlan.WorksIdS = mBAppWorks.WorksIdS;
        mBUploadPlan.WorksName = mBAppWorks.WorksName;
        mBUploadPlan.MusicID = mBAppWorks.MusicIdS;
        if (mAFileInfo != null) {
            mAFileInfo.RankArea = gAreaCode;
            mAFileInfo.IsRelease = true;
            switch (gWorksType) {
                case AWorksType.WORKS_SING_SONG:
                case AWorksType.WORKS_RECITATION:
                    ARecordInfo aRecordInfo = (ARecordInfo)mAFileInfo;
                    aRecordInfo.WorksName = mBUploadPlan.WorksName;
                    aRecordInfo.CoverFile = mBUploadPlan.CoverFile;
                    aRecordInfo.Intro = mBUploadPlan.Intro;
                    aRecordInfo.ClassStyle = gClassStyle;
                    if (aRecordInfo.TimeLength == 0){
                        MTOAST("文件时长不正确", 2000);
                        return;
                    }
                    break;
                case AWorksType.WORKS_OBB_SONG:
                case AWorksType.WORKS_OBB_RECITE:
                    AObbligInfo aObbligInfo = (AObbligInfo)mAFileInfo;
                    if (aObbligInfo.TimeLength == 0){
                        MTOAST("文件时长不正确", 2000);
                        return;
                    }
                    aObbligInfo.SongName = mBUploadPlan.WorksName;
                    aObbligInfo.CoverFile = mBUploadPlan.CoverFile;
                    aObbligInfo.Intro = mBUploadPlan.Intro;
                    aObbligInfo.ArtistName = mBAppWorks.ArtistName;
                    aObbligInfo.ClassStyle = gClassStyle;
                    mBUploadPlan.IsOriginal = cbOriginalUp.isChecked();
                    if (!mBUploadPlan.IsOriginal) {              // 上传伴奏
//                        aObbligInfo.MusicID0 = mSvrFound.MusicID0;
//                        aObbligInfo.MusicID1 = mSvrFound.MusicID1;
                        aObbligInfo.ClassStyle = gClassStyle;
                    }else {                                     // 上传原唱
                        if (mSvrFound != null) {
                            aObbligInfo.MusicID0 = mSvrFound.UserID;
                            aObbligInfo.MusicID1 = mSvrFound.FileID;
                        }
                        aObbligInfo.ClassStyle = gClassStyle | (1 << KCB_LIST_ORIGINAL_FLAG);
                    }
                    MLOG(String.format("aObbligInfo.MusicID %s_%04x %08x", aObbligInfo.MusicID0, aObbligInfo.MusicID1, aObbligInfo.ClassStyle));
                    break;
                case AWorksType.WORKS_TYPE_PHOTO:
                    APhotoInfo aPhotoInfo = (APhotoInfo)mAFileInfo;
                    if (mBAppWorks.Photos != null && mBAppWorks.Photos.length > 0) {
                        aPhotoInfo.FileName = "";
                        for (int index = 0; index < mBAppWorks.Photos.length; index++) {
                            String fileName = mBAppWorks.Photos[index].FileName;
                            if (MAPI.IS_FILE_DONE(fileName)) {
                                aPhotoInfo.FileName += fileName + ",";
                            }
                        }
                    }
                    if (MAPI.isEmpty(aPhotoInfo.FileName)){
                        aPhotoInfo.FileName = mBUploadPlan.CoverFile;
                    }
                    if (MAPI.isEmpty(aPhotoInfo.FileName)){
                        MTOAST("至少需要选择一张图片", 2000);
                        return;
                    }
                    aPhotoInfo.TitleName = mBUploadPlan.WorksName;
                    aPhotoInfo.Intro = mBUploadPlan.Intro;
                    break;
                case AWorksType.WORKS_BLOG_TEXT:
                    ATakeInfo aTakeInfo = (ATakeInfo)mAFileInfo;
                    aTakeInfo.FileName = mBUploadPlan.WorksName;
                    aTakeInfo.SubName = mBUploadPlan.Intro;
                    if (aTakeInfo.SubName != null && aTakeInfo.SubName.length() > 100){
                        aTakeInfo.SubName = aTakeInfo.SubName.substring(0, 99);
                    }
                    StringBuffer stringBuffer = new StringBuffer();
//                    <h1>hhhhhhhhhh</h1><p>aaaaaaaaa</p><img src="file:///data/user/0/ltd.topobbphoto/cache/photo/pedit24.jpg"/><img src="file:///data/user/0/ltd.topobbphoto/cache/photo/pedit26.jpg"/><p></p>
                    stringBuffer.append("<h1>");
                    stringBuffer.append(aTakeInfo.FileName);
                    stringBuffer.append("</h1>");
                    stringBuffer.append("<p>");
                    stringBuffer.append(mBUploadPlan.Intro);
                    stringBuffer.append("</p>");
                    if (mBAppWorks.Photos != null && mBAppWorks.Photos.length > 0) {
                        for (int index = 0; index < mBAppWorks.Photos.length; index++) {
                            String fileName = mBAppWorks.Photos[index].FileName;
                            if (MAPI.IS_FILE_DONE(fileName)) {
                                stringBuffer.append("<img src=\"file://");
                                stringBuffer.append(fileName);
                                stringBuffer.append("\"/>");
                            }
                        }
                        stringBuffer.append("<p></p>");
                        if (mBUploadPlan.CoverFile != null){
                            aTakeInfo.CoverFile = mBUploadPlan.CoverFile;
                        }else {
                            aTakeInfo.CoverFile = mBAppWorks.Photos[0].FileName;
                        }
                    }else {
                        aTakeInfo.CoverFile = mBUploadPlan.CoverFile;
                    }
                    if (MAPI.isEmpty(aTakeInfo.CoverFile)){
                        MTOAST("至少需要选择一张图片", 2000);
                        return;
                    }
                    text = stringBuffer.toString();
                    aTakeInfo.MainFile = String.format("%s%s.txt", MRAM.gsCachePath, MDBS.getDbsId());
                    MAPI.WRITE_BUFF8_FILE(text.getBytes().length, text.getBytes(), aTakeInfo.MainFile);
                    MLOG(String.format("aBlogInfo.TextFileA %s", text));
                    MLOG(String.format("aBlogInfo.TextFileB %s %s", MAPI.GET_FILE_LENGTH(aTakeInfo.MainFile), aTakeInfo.MainFile));
                    aTakeInfo.Intro = mBUploadPlan.Intro;
                    break;
            }
        }


        MDBS.setBUploadPlan(MAPP.mBDbsAccount, mBUploadPlan);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        MTOAST(String.format("将于%s上传%s", sdf.format(mBUploadPlan.SetTick), mBUploadPlan.WorksName), 3000);

        g4Local_1 = sysBitmap.getBitmapSize(mBUploadPlan.CoverFile);
        MLOG(String.format("mBUploadPlan.Intro Cover:%sx%s Intro:%s", g4Local_1>>16, g4Local_1&0xffff, mBUploadPlan.Intro));

        setPageResult(mBUploadPlan);
        setClose();
    }
    public boolean searchWorks(AUserSearchType aUserSearchType, BAppWorks bAppWorks, String kclFile) {
        MLOG(String.format("searchWorksA S1 A"));
        for (int retry = 0; retry < 3 ; retry++) {
            AFileInfo[] aFileInfos = App32.searchWorks(aUserSearchType, bAppWorks.WorksName);
            if (aFileInfos != null) {
                AKclFile aKclFile1 = MAPI.READ_KCL_FILE(kclFile);
                if (aKclFile1 != null && aKclFile1.Lines != null && aKclFile1.Lines.length > 0) {   // 有歌词
                    String worksName = null;
                    String artistName = null;
                    for (int index = 0; index < aFileInfos.length; index++) {
                        if (aFileInfos[index] == null){
                            continue;
                        }
                        worksName = mMyUtils.getFileName(aFileInfos[index]);
                        artistName = mMyUtils.getFileSubName(aFileInfos[index]);
                        int counter = 0;
                        for (counter = 0; counter < 500; counter++) {
                            worksName = mMyUtils.getFileName(aFileInfos[index]);
                            artistName = mMyUtils.getFileSubName(aFileInfos[index]);
                            if (worksName != null && artistName != null){
                                break;
                            }
                            MSLEEP(10);
                        }
                         MLOG(String.format("searchWorksA S1 %s/%s %s_%04x %s_%s(%s_%s)%s_%s", index + 1, aFileInfos.length, aFileInfos[index].UserID, aFileInfos[index].FileID, worksName, artistName, bAppWorks.WorksName, bAppWorks.ArtistName, counter, retry));
                        if (bAppWorks.WorksName.equals(worksName) && bAppWorks.ArtistName.equals(artistName)) {  // 歌名及歌手完全相同
                            String fileName = String.format("%stemp.kcl", MRAM.gsCachePath);
                            MAPI.DELETE_FILE(fileName);
                            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(128);
                            int type = mMyUtils.getWorksRoomType(AFileType.FILE_LYRIC);
                            String result = mMyUtils.threadDownloadFiles(type, aFileInfos[index].UserID, aFileInfos[index].FileID, 0, 0, null, fileName, byteBuffer);
                            if ("ok".equals(result)) {
                                AKclFile aKclFile2 = MAPI.READ_KCL_FILE(kclFile);
                                if (aKclFile2 != null && aKclFile2.Lines != null) {
                                    MLOG(String.format("searchWorksA S5 %s %s(%s)", index, aKclFile1.Lines.length, aKclFile2.Lines.length));
                                    mSvrFound = aFileInfos[index];
                                    return true;                     // 必须完全相同
                                }
                                MLOGE(String.format("searchWorksA S4 %s", aKclFile2));
                            }
                            MLOGE(String.format("searchWorksA S2 %s(%s)%s_%04x(%s)%s", index + 1, result, aFileInfos[index].UserID, aFileInfos[index].FileID, worksName, artistName));

                        }
                    }
                }
            }
            MAPI.MSLEEP(1000);
        }
        return false;
    }
    private void famousHead(BAppWorks bAppWorks) {
        if (!MAPI.isEmpty(bAppWorks.ArtistName)) {
            TaskApp3f taskApp3f = new TaskApp3f();
            String artistName = bAppWorks.ArtistName.replace(",", " ");
            artistName = artistName.replace("，", " ");
            artistName = artistName.replace("、", " ");
            String[] split = artistName.split(" ");
            List<APhotoInfo> lists = new ArrayList<>();
            for (int index = 0; index < split.length; index++) {
                final String text = split[index];
                MRAM.mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MTOAST(String.format("正在查找%s头像", text), 2000);
                    }
                });
                ABean aBean = taskApp3f.famousHead(false, text);
                if (aBean != null && aBean.mBean != null && aBean.mBean.size() > 0) {
                    lists.addAll((List) aBean.mBean);
                }
            }
            if (lists.size() > 0) {
                mAPhotoInfo = lists.toArray(new APhotoInfo[lists.size()]);
            } else {
                mAPhotoInfo = new APhotoInfo[1];
                mAPhotoInfo[0] = new APhotoInfo();
                mAPhotoInfo[0].FileUrl = bAppWorks.ArtistIcon;
            }
        }
    }

    private void setCoverFile(String coverFile) {
        mBUploadPlan.CoverFile = coverFile;
        SysBitmap sysBitmap = new SysBitmap();
        int g4Local_1 = sysBitmap.getBitmapSize(coverFile);
        gCoverWidth = g4Local_1 >> 16;
        gCoverHeight = g4Local_1 & 0xffff;
        MLOG(String.format("WORKS_OBB_SONG E80 %s %s", MAPI.GET_FILE_LENGTH(mBUploadPlan.CoverFile), mBUploadPlan.CoverFile));
    }
    private String getDownloadFlag(){
        if (((gDownloadFlag & 0x01) != 0)) {
            return "视频作品出错";     // ERROR
        }
        if (((gDownloadFlag & 0x02) != 0)){
            return "音频作品出错";     // ERROR
        }
        if (((gDownloadFlag & 0x04) != 0)){
            return "获取时长出错";          // ERROR
        }
        if (((gDownloadFlag & 0x08) != 0)){
            return "歌词出错";          // ERROR
        }

        if (((gDownloadFlag & 0x10) != 0)){
            return "伴奏文件出错";          // ERROR
        }
        if (((gDownloadFlag & 0x20) != 0)){
            return "原唱文件出错";          // ERROR
        }
        return null;
    }

    private BUploadPlan makeBUploadPlan(){
        BUploadPlan bUploadPlan= new BUploadPlan();
        Object object = MDBS.getFreeText( 0, "UPLOAD_DATE_TIME");
        bUploadPlan.SetTick = System.currentTimeMillis();
        if (object instanceof Long) {
            long datetime = (Long) object;
            if (datetime > bUploadPlan.SetTick) {
                bUploadPlan.SetTick = datetime;
            }
        }
        if (gWorksType != AWorksType.WORKS_OBB_SONG && gWorksType != AWorksType.WORKS_OBB_RECITE) {     // 伴奏一般需要马上上传
            bUploadPlan.SetTick += (11 * 60 * 1000);                                // 11分钟之后
        }
        return bUploadPlan;
    }
    private boolean changeAPhotoInfo(){
        if (mAPhotoInfo != null){
            APhotoInfo aPhotoInfo = mAPhotoInfo[gAPhotoInfo % mAPhotoInfo.length];
            if (!MAPI.IS_FILE_DONE(aPhotoInfo.FileName)){
                EditUtils editUtils = new EditUtils();
                if (aPhotoInfo.FileName == null){
                    SysUtils sysUtils = new SysUtils();
                    aPhotoInfo.PhotoID = sysUtils.getStringMd5(aPhotoInfo.FileUrl);
                    aPhotoInfo.FileName = String.format("%sA%s.jpg", MRAM.gsCachePath, aPhotoInfo.PhotoID);
                }
                if ("ok".equals(editUtils.downloadPhoto(false, 800, 800, aPhotoInfo.FileUrl, aPhotoInfo.FileName))) {
                    setCoverFile(aPhotoInfo.FileName);
                }
            }else {
                setCoverFile(aPhotoInfo.FileName);
            }
            gPhotoQty = mAPhotoInfo.length;
            ++gAPhotoInfo;
            return true;
        }
        return false;
    }
    private void clickCover(final boolean click){
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                    MLOG(String.format("clickCover A %s", skipAPhotoInfo));
                    if (!skipAPhotoInfo && changeAPhotoInfo()){
                        MLOG("clickCover A1");
                        return;
                    }
                    if (mTaskApp3f == null){
                        mTaskApp3f = new TaskApp3f();
                    }
                    int table = mTaskApp3f.keyword2Table(gsKeyWord);
                    List<APhotoInfo> lists = (List) MSKIN.getDbsList(VARIA.DBS_PHOTO_NETWORK, table);
//                    MLOG(String.format("clickCover B %s(%s)%s(%s)", lists!=null?lists.size():0, table, gsKeyWord, MSKIN.getErrorObject()));
//                    if (!MAPI.isEmpty(MSKIN.getErrorObject())){
////                        MAPI.DELETE_FILE(MSKIN.getErrorObject());
//                    }
                    if ((lists == null || lists.size() == 0)){
                        if (click) {
                            MLOG(String.format("clickCover C %s", gsKeyWord));
                            // 0x0f << 8 = 0xf00 = 4096;
                            mTaskApp3f.searchPhoto((byte) 0x0f, (byte) 0, gsKeyWord, new KcTwoListener() {
                                @Override
                                public void onMessage(Object object1, Object object2) {
                                    if (object1 instanceof Integer && object2 instanceof Integer) {
                                        final int temp1 = (int)object1;
                                        final int temp2 = (int)object2;
                                        if (temp1 != temp2) {
                                            MRAM.mActivity.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MSKIN.setText(String.format("找到%s", temp1), kbtChangeUpload);
                                                }
                                            });
                                        }else {
                                            clickCover(false);
                                        }
                                    }else if (object1 == null){
                                        mTaskApp3f = null;
                                        MRAM.mActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                MSKIN.setText(String.format("找到%s", gsKeyWord), kbtChangeUpload);
                                            }
                                        });

                                    }
                                }
                            });
                        }
                        return;
                    }
                    int size = 800;
                    int quality = 60;
                    table = mTaskApp3f.keyword2Table(gsKeyWord);
                    int length = lists.size();
                    SysUtils sysUtils = new SysUtils();
                    SysBitmap sysBitmap = new SysBitmap();
                    MLOG("clickCover D");
                    for (int index = 0; index < length; index++) {
                        APhotoInfo aPhotoInfo = lists.get(index);
                        if (aPhotoInfo != null) {
                            MSKIN.delDbsItem(VARIA.DBS_PHOTO_NETWORK, table, aPhotoInfo.PhotoID);
                            sysUtils.getUrlFile(aPhotoInfo.FileUrl, aPhotoInfo.FileName);
                            int g4Local_1 = sysBitmap.getBitmapSize(aPhotoInfo.FileName);
                            int width = g4Local_1 >> 16;
                            int height = g4Local_1 & 0xffff;
                            if (width >= size && height >= size) {
                                Bitmap bitmap = sysBitmap.getReqBitmap(size, size, 0, 0, 0, 0, 0, aPhotoInfo.FileName);
                                if (bitmap != null) {
//                                    MLOG(String.format("TaskApp3f bitmap %s/%s %sx%s(%sx%s)%s", index, length, bitmap.getWidth(), bitmap.getHeight(), width, height, aPhotoInfo.FileUrl));
                                    String localFile = String.format("%s.jpg", aPhotoInfo.FileName);
                                    if (sysBitmap.saveBitmapFile(bitmap, localFile, quality)){
                                        setCoverFile(localFile);
//                                        mBUploadPlan.CoverFile = localFile;
                                        gPhotoQty = MSKIN.getDbsSize(VARIA.DBS_PHOTO_NETWORK, table);
                                        bitmap.recycle();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    MLOG("clickCover C");
                    return;
                }
                showInfo();
            }
        });
    }




    public void showDateDialog() {
        Calendar calendar = Calendar.getInstance(Locale.CHINA);        // 创建一个日历引用d，通过静态方法getInstance() 从指定时区 Locale.CHINA 获得一个日期实例
        calendar.setTime(new Date(mBUploadPlan.SetTick));
        int themeresid = 2;                             // themeresid表示的是效果的背景色，设置为2就是上面的效果图
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), themeresid, new DatePickerDialog.OnDateSetListener(){
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date(mBUploadPlan.SetTick));
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    String input = String.format("%04d-%02d-%02d %02d:%02d", year, monthOfYear+1, dayOfMonth, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
                    Date date = format.parse(input);
                    MLOG(String.format("makeDataA %s %s %s", input, date.getTime(), System.currentTimeMillis()));
                    mBUploadPlan.SetTick = date.getTime();
                    showInfo();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.setMessage("请选择日期");
        datePickerDialog.show();
    }
    private void showTimeDialog() {
        Calendar calendar = Calendar.getInstance(Locale.CHINA);        // 创建一个日历引用d，通过静态方法getInstance() 从指定时区 Locale.CHINA 获得一个日期实例
        calendar.setTime(new Date(mBUploadPlan.SetTick));
        int themeresid = 2;                             // themeresid表示的是效果的背景色，设置为2就是上面的效果图
        TimePickerDialog timeDialog = new TimePickerDialog(getActivity(), themeresid, new TimePickerDialog.OnTimeSetListener() {                //从这个方法中取得获得的时间
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date(mBUploadPlan.SetTick));
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    String input = String.format("%04d-%02d-%02d %02d:%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
                    Date date = format.parse(input);
                    MLOG(String.format("makeDataA %s %s %s", input, date.getTime(), System.currentTimeMillis()));
                    mBUploadPlan.SetTick = date.getTime();
                    showInfo();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);        // 是否采用24小时制
        timeDialog.show();
    }
    private void getKeyWord(boolean isChange){
        int index = MDBS.getFreeInt(gWorksType, "EditUploadPage");
        if (!isChange && index < 0x100){
            gsKeyWord = "封面";
            return;
        }
        String[] app3f_keyword = MSKIN.getStringArray(R.array.app3f_keyword);
        gsKeyWord = app3f_keyword[index % app3f_keyword.length];
        if (isChange){
            if (index < 0x100){
                index = 0x100;
            }
            MDBS.setFreeInt(gWorksType, "EditUploadPage", index+1);
        }
    }

}